﻿#define IsUsed
//#define Is

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;




namespace Demo_MVVM基本框架
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = ViewModel.ViewModel.GetInstance().m_Model_MainWindow;


        }

#if IsUsed

        private CancellationTokenSource CtsTaskUpdateUI = new CancellationTokenSource();
        private Task TaskUpdateUI = null;

#elif Is

        private CancellationTokenSource CtsTaskUpdateUI = new CancellationTokenSource();
        private Task TaskUpdateUI = null;

#endif

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            TaskUpdateUI = new Task(new Action(() => { UpdateUI(CtsTaskUpdateUI.Token); }), CtsTaskUpdateUI.Token);
            TaskUpdateUI.Start();
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            CtsTaskUpdateUI.Cancel();
        }

        private void UpdateUI(CancellationToken ct)
        {
            try
            {
                while (!ct.IsCancellationRequested)
                {
                    ////同步委托
                    //System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate ()
                    //{
                    //    ((MainWindow)System.Windows.Application.Current.MainWindow).MyView.Demo();
                    //});

                    //异步委托
                    //System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate ()
                    //{
                    //    ((MainWindow)System.Windows.Application.Current.MainWindow).MyView.Demo();
                    //});

                    Thread.Sleep(20);
                }
            }
            catch (Exception ex)
            {
            }
        }

    }
}
